package com.lajiaomian.springbootruijiwaimai.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author lajiaomian
 * @create 2022-08-11-22:52
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@Slf4j
@ResponseBody
public class GloablExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> gloablExceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.info("异常为:{}"+ex);
        if(ex.getMessage().contains("Duplicate entry")){
            String[] msg = ex.getMessage().split(" ");
            return R.error(msg[2] + "已存在");
        }

        return R.error("未知错误");

    }
    @ExceptionHandler(MyException.class)
    public R<String> gloablExceptionHandler(MyException ex){
        log.info("异常为:{}"+ex);

        return R.error(ex.getMessage());

    }
}
